<?php

namespace App\Models\Api;

use App\Models\Admin\StoreGoodsViewPermissions;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;

class GoodsStore extends Model
{

    protected $table = 'goods_store';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U'; // 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 获取促销
     * @param $store_id
     * @param int $limit
     * @return mixed
     */
    public static function getPromotionList($store_id, $limit = 8)
    {
        $list = self::from('goods_store as sg')
            ->select(['sg.id', 'sg.goods_id', 'g.goods_sn', 'g.goods_img', 'g.goods_name', 'sg.mini_quantity', 'g.goods_price', 'g.is_group', 'g.goods_sale_num', 'sg.sale_price', 'c.cate_name', 'sg.buy_num', 'sg.get_num'])
            ->leftJoin('goods as g', 'g.id', '=', 'sg.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->where(['sg.store_id' => $store_id, 'g.promotion' => 1])
            ->where(['g.status' => 1])
            ->orderBy('sg.id', 'desc')
            ->limit($limit)->get();
        // $is_agent = Store::where(['id' => $store_id])->value('is_agent');
        // foreach ($list as $key => $value) {
        //     $list[$key]['mini_quantity'] = $value['mini_quantity'];
        // }
        return $list;
    }

    /**
     * 获取列表
     */
    public static function getListBySid($params, $promotion = 0, $limit = 8)
    {
        $where = [];
        $allowedGoodsIds = [];

        // 如果有传入store_id，检查代理商权限
        if (!empty($params['store_id'])) {
            $where[] = ['sg.store_id', '=', $params['store_id']];

            // 获取代理商可查看的商品ID列表
            $permission = StoreGoodsViewPermissions::where('store_id', $params['store_id'])->first();

            if ($permission && !empty($permission->goods_ids)) {
                // 处理goods_ids，确保格式正确
                $allowedGoodsIds = array_filter(explode(',', $permission->goods_ids));
                $allowedGoodsIds = array_map('intval', $allowedGoodsIds);
            }
        }

        // 其他筛选条件
        if (!empty($params['goods_name'])) {
            $where[] = ['g.goods_name', 'like', "%{$params['goods_name']}%"];
        }
        if (!empty($params['goods_sn'])) {
            $where[] = ['g.goods_sn', '=', $params['goods_sn']];
        }
        if (!empty($params['cate_id'])) {
            $where[] = ['g.cate_id', '=', $params['cate_id']];
        }

        // 基础条件
        $where[] = ['g.promotion', '=', $promotion];
        $where[] = ['g.status', '=', 1];
        $where[] = ['g.goods_type', '=', $params['type']];

        // 如果代理商没有允许查看的商品ID，则直接返回空数据（分页格式）
        if (empty($allowedGoodsIds) && !empty($params['store_id'])) {
            // 创建一个空集合
            $items = collect([]);
            // 当前页码，默认为1
            $page = LengthAwarePaginator::resolveCurrentPage();
            // 每页显示数量
            $perPage = $limit;
            // 创建一个新的分页实例
            $paginatedItems = new LengthAwarePaginator($items, 0, $perPage, $page, [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
            ]);
            return $paginatedItems;
        }
        // 构建查询
        $query = self::from('goods_store as sg')
            ->select([
                'sg.id',
                'sg.goods_id',
                'g.goods_sn',
                'sg.mini_quantity',
                'g.goods_img',
                'g.goods_name',
                'g.goods_price',
                'g.is_group',
                'g.goods_sale_num',
                'sg.sale_price',
                'c.cate_name',
                'sg.buy_num',
                'sg.get_num'
            ])
            ->leftJoin('goods as g', 'g.id', '=', 'sg.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->where($where);

        // 如果有权限限制，添加商品ID过滤
        if (!empty($allowedGoodsIds)) {
            $query->whereIn('g.id', $allowedGoodsIds);
        }

        return $query->orderBy('g.id', 'desc')->paginate($limit);
    }
    /**
     * 获取订单提交的商品
     */
    public static function getOrderByGoodsId($store_id, $goods_id, $num = 1)
    {
        $goodsInfo = GoodsStore::from('goods_store as gs')
            ->leftJoin('goods as g', 'g.id', '=', 'gs.goods_id')
            ->where(['gs.store_id' => $store_id, 'gs.goods_id' => $goods_id])
            ->select(['gs.goods_id', 'g.goods_img', 'g.goods_name', 'g.mini_quantity', 'gs.sale_price', 'gs.buy_num', 'gs.get_num'])->first();
        if ($goodsInfo) {
            //            $num = ($num < $goodsInfo['mini_quantity']) ? $goodsInfo['mini_quantity'] : $num;
            $pamas['goods_list'][] = ['goods_id' => $goodsInfo['goods_id'], 'is_give' => 0, 'goods_name' => $goodsInfo['goods_name'], 'goods_img' => $goodsInfo['goods_img'], 'goods_num' => $num, 'sale_price' => $goodsInfo['sale_price']];
            if (($num > $goodsInfo['buy_num']) && ($goodsInfo['get_num'] > $goodsInfo['buy_num'])) {
                $newNum = intval($num / $goodsInfo['buy_num']) * $goodsInfo['get_num'];
                $pamas['goods_list'][] = ['goods_id' => $goodsInfo['goods_id'], 'is_give' => 1, 'goods_name' => $goodsInfo['goods_name'], 'goods_img' => $goodsInfo['goods_img'], 'goods_num' => $newNum, 'sale_price' => $goodsInfo['sale_price']];
            }
            $pamas['mini_quantity'] = $goodsInfo['mini_quantity'];
            $pamas['money'] = $goodsInfo['sale_price'] * $num;
            $pamas['sale_price'] = $goodsInfo['sale_price'];
            $pamas['num'] = $newNum + $num;
            return $pamas;
        }
        return false;
    }

    /**
     * 获取详情
     * @param $parame
     * @return mixed
     */
    public static function getInfo($parame)
    {
        $where = array();
        if ($parame['id']) {
            $where[] = ['gs.id', '=', $parame['id']];
        }
        if ($parame['goods_id']) {
            $where[] = ['gs.goods_id', '=', $parame['goods_id']];
        }
        if ($parame['store_id']) {
            $where[] = ['gs.store_id', '=', $parame['store_id']];
        }

        $field = [
            'gs.id', 'g.id as goods_id', 'g.goods_sn', 'g.goods_weight_m', 'g.goods_img_list', 'g.goods_name', 'g.goods_price', 'g.goods_group', 'gs.mini_quantity', 'g.send_require',
            'g.send', 'g.goods_detail', 'g.is_group', 'g.goods_sale_num', 'gs.sale_price', 'c.cate_name', 'gs.buy_num', 'gs.get_num'
        ];
        $info = self::from('goods_store as gs')
            ->select($field)
            ->leftJoin('goods as g', 'g.id', '=', 'gs.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->where($where)
            ->first()
            ->toArray();

        return $info;
    }
}
